package com.to8to.scene.server;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.to8to.commons.json.JSONArray;
import com.to8to.commons.json.JSONObject;
import com.to8to.commons.json.JSONValue;
import com.to8to.commons.mongo.MongoClientBase;

public class Tables
{

    public static String Scene = "scene"; //id autoinc

    public static String Diary = "diary"; //id autoinc

    public static String Product = "product"; //id autoinc

    public static String Comment = "comment"; //id autoinc

    public static String Message = "message"; //id autoinc

    public static String Behavior = "behavior"; //id autoinc

    public static String UserScore = "user_score"; //id autoinc

    //	public static String DiaryProduct = "diary_product";  //id autoinc

    public static String StaticConfigValue = "static_config_value";//for 2.5
    
    public static String StaticConfigOld = "static_config_old";//for 2.0

    //    public static void ensureAllIndexes(MongoClientBase mongo) throws FileNotFoundException
    //    {
    //        URL index_url = ClassLoader.getSystemClassLoader().getResource("index.json");
    //        if (null == index_url)
    //            return;
    //        String index_file_path = FileUtil.getAbsPath("index.json");
    //        File index_file = new File(index_file_path);
    //        if (index_file.exists())
    //            ensureAllIndexes(mongo, new FileInputStream(index_file));
    //    }

    /**
     * 可以支持联合索引了
     * @param mongo
     */
    public static void ensureAllIndexes(MongoClientBase mongo, InputStream input)
    {
        //        List<String> lines = FileUtil.readLines("index.json");
        //        List<String> lines = new ArrayList<String>();
        //        for (String line : FileUtil.readLines(input, "utf-8"))
        //        {
        //            lines.add(line);
        //        }

        try
        {
            String json = IOUtils.toString(input, "utf-8");
            JSONObject index = (JSONObject) JSONValue.parse(json);
            for (String table : index.keySetString())
            {
                JSONArray indexs = index.getJSONArray(table);
                for (int i = 0; i < indexs.size(); i++)
                {
                    JSONObject idx = (JSONObject) indexs.get(i);
                    DBObject dbObject = new BasicDBObject();
                    for (Object key : idx.keySet())
                    {
                        dbObject.put((String) key, idx.getInt(key));
                    }
                    mongo.ensureIndex(table, dbObject);
                }
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //        Joiner joiner = Joiner.on(" ").skipNulls();
        //        String json = joiner.join(lines);

    }
}
